/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-09-25 15:01:04
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-09-27 11:08:35
 * @FilePath: /Learn/sem_cp/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
#include<string>
#include"Task.hpp"
#include "Ringqueue.hpp"
using namespace std;

struct ThreadData
{
    RingQueue<Task>*rq;
    string threadname;
};
void *Productor(void *args)
{
    // sleep(3);
    ThreadData *td=static_cast<ThreadData*>(args);
    RingQueue<Task>*rq=td->rq;
    string name=td->threadname;
    int len=opers.size();
    while (1)
    {
        // 1.获取数据
        int data1 = rand() % 10 + 1;
        int data2=rand() % 10;
        char op=opers[rand()%len];
        // 2.生产数据
        Task t(data1,data2,op);
        rq->Push(t);
        std::cout << "Product data done,data is: " << t.getTask()<<"who:"<<name << endl;
    }
    return nullptr;
}

void *Consumer(void *args)
{
    ThreadData *td=static_cast<ThreadData*>(args);
    RingQueue<Task>*rq=td->rq;
    string name=td->threadname;
    while (1)
    {
        // 1.消费数据
        Task t;
        rq->Pop(&t);
        std::cout << "Consumer get data,data is: " <<t.getTask()
        <<"who:"<<name <<"result:"<<t.Getresult() <<endl;
        sleep(1);
        // 2.处理数据
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr)); // 加强随机性
    //属于共享区中的内容
    RingQueue<Task> *rq = new RingQueue<Task>(5);
    pthread_t c[5], p[3];
    for (int i = 0; i < 3; i++)
    {
        ThreadData*td=new ThreadData();
        td->rq=rq;
        td->threadname="Product-"+to_string(i);
        pthread_create(p + i, nullptr, Productor, td);
    }
    for (int i = 0; i < 5; i++)
    {
        ThreadData*td=new ThreadData();
        td->rq=rq;
        td->threadname="Consumer-"+to_string(i);
        pthread_create(c + i, nullptr, Consumer, td);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 3; i++)
    {
        pthread_join(p[i], nullptr);
    }
    return 0;
}